<template>
  <el-row>
    <el-col :span="5">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick"/>
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="19">
      <basic-container>
        <avue-crud :option="option"
                  :table-loading="loading"
                  :data="data"
                  ref="crud"
                  v-model="form"
                  :permission="permissionList"
                  :before-open="beforeOpen"
                  :before-close="beforeClose"
                  @row-del="rowDel"
                  @row-update="rowUpdate"
                  @row-save="rowSave"
                  @search-change="searchChange"
                  @search-reset="searchReset"
                  @selection-change="selectionChange"
                  @current-change="currentChange"
                  @size-change="sizeChange"
                  @refresh-change="refreshChange"
                  @on-load="onLoad"
                  >
          <template slot="menuLeft">
            <el-button type="danger"
                      size="small"
                      icon="el-icon-delete"
                      v-if="permission.dept_delete"
                      plain
                      @click="handleDelete">删 除
            </el-button>
          </template>
          <!-- <template slot-scope="scope" slot="menu">
            <el-button
              type="text"
              icon="el-icon-circle-plus-outline"
              size="small"
              @click.stop="handleAdd(scope.row,scope.index)"
              v-if="userInfo.role_name.includes('admin')"
            >新增下级
            </el-button>
          </template> -->
          <template slot-scope="{row}"
                    slot="deptCategory">
            <el-tag>{{row.deptCategoryName}}</el-tag>
          </template>
          <!-- <template slot-scope="{row}"
                    slot="gridId">
            <el-tag>{{row.gridId}}</el-tag>
          </template>
          <template slot-scope="{row}"
                    slot="status">
            <el-tag>{{row.status}}</el-tag>
          </template> -->
        </avue-crud>
        <el-dialog title="选择网格划分"
          ref="gridDialog"
            append-to-body
            :visible.sync="flowBox"
            :fullscreen="false"
            style="width:100%;height:900px;">
          <grid-map style="height:600px;" v-on:getGridData="getGridMap($event)" :deptId="form.id ? form.id :''" />
        </el-dialog>
      </basic-container>
    </el-col>
  </el-row>
</template>
<script>
  import {
    getLazyList,
    remove,
    update,
    add,
    getDept,
    getDeptTree,
    getDeptLazyTree,
    getCodeByPid
  } from "@/api/system/dept";
  import {mapGetters} from "vuex";
 // import website from '@/config/website';
 import { validatenull,isvalidatemobile,validatenum,validatefloat} from "@/util/validate";

  import gridMap from '@/components/gis/gridMap'

  export default {
    data() {
       //手机号校验
      const validatePhone = (rule, value, callback) => {
         if(validatenum(value,1)){
            if (isvalidatemobile(value)[0]) {
              callback(new Error(isvalidatemobile(value)[1]));
            } else {
              callback();
            }
         }else{
           callback();
         }
      };

      //校验正整数 非必输
       const validateNum = (rule, value, callback) => {
        if(!validatenull(value)){
          if(validatenum(value,1)){
            callback("请输入正整数")
          }else {
            callback();
          }
        }else{
          callback();
        }
      };
      //校验正浮点数
      const validateFloat = (rule ,value, callback) => {
         if(!validatenull(value)){
            if(validatefloat(value)){
              callback();
            }else{
              callback("请输入正确的数字");
            }
         }else{
           callback();
         }
      };
      return {
        flowBox: false,
        form: {
        },
        selectionList: [],
        query: {},
        loading: true,
        parentId: 0,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0,
        },
        init: {
          deptTree: [],
        },
        treeDeptId: '',
        treeData: [],
        treeOption: {
          nodeKey: 'id',
          lazy: true,
          treeLoad: (node, resolve)=>{
            const parentId = (node.level === 0) ? 0 : node.data.id;
            getDeptLazyTree(parentId).then(res => {
              this.parentId = res.data.data[0].id
              resolve(res.data.data.map(item => {
                return {
                  ...item,
                  leaf: !item.hasChildren
                }
              }))
            });
          },
          addBtn: false,
          menu: false,
          size: 'small',
          props: {
            labelText: '标题',
            label: 'title',
            value: 'value',
            children: 'children'
          }
        },


        option: {
          // lazy: true,
          tip: false,
          simplePage: true,
          searchShow: true,
          searchMenuSpan: 6,
          // tree: true,
          border: true,
          index: true,
          selection: true,
          viewBtn: true,
          menuWidth: 300,
          //addBtn: false,
          dialogClickModal: false,
          column: [
             {
              label: "上级组织",
              prop: "parentId",
              dicData: [],
              type: "tree",
              hide: true,
              disabled: true,
              props: {
                label: "title"
              },
              rules: [{
                required: false,
                message: "请选择上级组织",
                trigger: "click"
              }]
            },
            {
              label: "组织名称",
              prop: "deptName",
              search: true,
              width: 250,
              rules: [{
                required: true,
                message: "请输入机构名称",
                trigger: "blur"
              }]
            },
            {
              label: "所属租户",
              prop: "tenantId",
              type: "tree",
              dicUrl: "/api/smart-system/tenant/select",
              addDisplay: false,
              editDisplay: false,
              //viewDisplay: website.tenantMode,
              viewDisplay: false,
              span: 24,
              props: {
                label: "tenantName",
                value: "tenantId"
              },
              //hide: !website.tenantMode,
              hide: true,
              //search: website.tenantMode,
              search: false,
              rules: [{
                required: true,
                message: "请输入所属租户",
                trigger: "click"
              }]
            },
            // {
            //   label: "机构全称",
            //   prop: "fullName",
            //   search: true,
            //   rules: [{
            //     required: true,
            //     message: "请输入机构全称",
            //     trigger: "blur"
            //   }]
            // },
           {
              label: "组织编码",
              prop: "deptCode",
              search: true,
              rules: [{
                required: true,
                message: "请输入组织编码",
                trigger: "blur"
              }]
            },
            {
              label: "机构类型",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=org_category",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
              width: 120,
              prop: "deptCategory",
              slot: true,
              rules: [{
                required: true,
                message: "请输入机构类型",
                trigger: "blur"
              }]
            },
            {
              label: "排序",
              prop: "sort",
              type: "number",
              align: "right",
              width: 80,
              rules: [{
                required: true,
                message: "请输入排序",
                trigger: "blur"
              }]
            },
            {
              label:"网格状态",
              prop: "gridId",
              type: "select",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              dicData: [
                    {
                      label: "--",
                      value: 0
                    },
                    {
                      label: "未划分",
                      value: 1
                    },
                    {
                      label: "已划分",
                      value: 2
                    }
                  ],
            },
            {
              label: "组织状态",
              prop: "status",
              type: "radio",
              dicData: [
                    {
                      label: "正常",
                      value: 1
                    },
                    {
                      label: "停用",
                      value: 2
                    }
                  ],
              rules: [{
                required: true,
                message: "请输入组织状态",
                trigger: "blur"
              }]
            },
            {
              label: "网格员数量",
              prop: "goNum",
              type: "input",
              hide: true,
               display: true,
              rules: [{
                required: false,
                message: "请输入正确的网格员数量",
                validator: validateNum,
                trigger: "blur"
              }]
            },
            {
              label: "网格户数",
              prop: "gridHcount",
              type: "input",
              hide: true,
              display: true,
              rules: [{
                required: false,
                message: "请输入正确网格户数",
                validator: validateNum,
                trigger: "blur"
              }]
            },
            {
              label: "网格面积",
              prop: "girdArea",
              type: "input",
              hide: true,
              display: true,
              rules: [{
                required: false,
                message: "请输入正确的数字",
                validator: validateFloat,
                trigger: "blur"
              }]
            },
             {
              label: "网格划分",
              prop: "gridDraw",
              type: "map",
              display: true,
              hide: true,
              props: {
                label: "gridDraw",
                value: "12.1234,12.1244"
              },
              // rules: [{
              //   required: false,
              //   message: "请选择网格划分",
              //   validator: validateFloat,
              //   trigger: "click"
              // }],
              click:()=>{
                this.openGrid()
              }
            },
            {
              label: '网格颜色',
              prop: 'gridColor',
              type: 'color',
               display: true,
              hide: true,
            },
            {
              label: '网格介绍',
              prop: 'gridBrief',
              type: 'textarea',
              hide: true,
              display: true,
              span: 24
            },
            {
              label: "机构层级",
              prop: "deptGrade",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=sys_center_level",
              hide: true,
              display: false,
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入机构层级",
                trigger: "blur"
              }],
            },
           {
              label: "机构类型",
              prop: "orgType",
              type: "select",
              dicUrl: "/api/smart-system/dict-biz/dictionary?code=sys_dept_type",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              display: false,
              hide: true,
              rules: [{
                required: true,
                message: "请输入机构类型",
                trigger: "blur"
              }],
            },
            {
              label: "负责人",
              prop: "leader",
              type: "input",
              hide: true,
              display: false,
              rules: [{
                required: false,
                message: "请输入负责人",
                trigger: "blur"
              }]
            },
           {
              label: "电话",
              prop: "phone",
              type: "input",
              hide: true,
              display: false,
              rules: [{
                required: false,
                validator: validatePhone,
                message: "请输入正确手机号",
                trigger: "blur"
              }]
            },
            {
              label: "组成单位",
              prop: "component",
              type: "input",
              hide: true,
              display: false,
              span: 24,
              rules: [{
                required: false,
                message: "请输入组成单位",
                trigger: "blur"
              }]
            },
            {
              label: "所在地",
              prop: "location",
              type: "input",
              hide: true,
              display: false,
              rules: [{
                required: false,
                message: "请输入所在地",
                trigger: "blur"
              }]
            },
            {
              label: "邮箱",
              prop: "email",
              type: "input",
              hide: true,
              display: false,
              rules: [{
                required: false,
                message: "请输入邮箱",
                trigger: "blur"
              }]
            },
            {
              label: "经度",
              prop: "lng",
              type: "input",
              hide: true,
              display: false,
              rules: [{
                required: false,
                message: "请输入经度",
                trigger: "blur"
              }]
            },
            {
              label: "纬度",
              prop: "lat",
              type: "input",
              hide: true,
              display: false,
              rules: [{
                required: false,
                message: "请输入纬度",
                trigger: "blur"
              }]
            },
            {
              label: "所在地详址",
              prop: "address",
              type: "input",
              hide: true,
              display: false,
              rules: [{
                required: false,
                message: "请输入详址",
                trigger: "blur"
              }]
            },
          ]
        },
        data: []
      };
    },
    components: {
      gridMap
    },
    watch:{
      'form.deptCategory':{
            handler(val){
              //var deptCategory =this.findObject(this.option.column,'deptCategory').;
              const goNum =this.findObject(this.option.column,'goNum');
              const gridHcount =this.findObject(this.option.column,'gridHcount');
              const girdArea =this.findObject(this.option.column,'girdArea');
              const gridDraw =this.findObject(this.option.column,'gridDraw');
              const gridColor =this.findObject(this.option.column,'gridColor');
              const gridBrief =this.findObject(this.option.column,'gridBrief');
              const centerLevel =this.findObject(this.option.column,'deptGrade');
              const orgType =this.findObject(this.option.column,'orgType');
              const leader =this.findObject(this.option.column,'leader');
              const phone =this.findObject(this.option.column,'phone');
              const component =this.findObject(this.option.column,'component');
              const location =this.findObject(this.option.column,'location');
              const email =this.findObject(this.option.column,'email');
              const lng =this.findObject(this.option.column,'lng');
              const lat =this.findObject(this.option.column,'lat');
              const address =this.findObject(this.option.column,'address');
              if(val==1){
                goNum.display = true;
                gridHcount.display = true;
                girdArea.display = true;
                gridDraw.display = true;
                gridColor.display = true;
                gridBrief.display = true;
                centerLevel.display = false;
                orgType.display = false;
                leader.display = false;
                phone.display = false;
                component.display = false;
                location.display = false;
                email.display = false;
                lng.display = false;
                lat.display = false;
                address.display = false;
              }else if(val==2){
                goNum.display = false;
                gridHcount.display = false;
                girdArea.display = false;
                gridDraw.display = false;
                gridColor.display = false;
                gridBrief.display = false;
                centerLevel.display = true;
                orgType.display = true;
              }else{
                goNum.display = false;
                gridHcount.display = false;
                girdArea.display = false;
                gridDraw.display = false;
                gridColor.display = false;
                gridBrief.display = false;
                centerLevel.display = false;
                orgType.display = false;
              }
            },
            immediate: true
          },
     'form.orgType':{
            handler(val){
              const leader =this.findObject(this.option.column,'leader');
              const phone =this.findObject(this.option.column,'phone');
              const component =this.findObject(this.option.column,'component');
              const location =this.findObject(this.option.column,'location');
              const email =this.findObject(this.option.column,'email');
              const lng =this.findObject(this.option.column,'lng');
              const lat =this.findObject(this.option.column,'lat');
              const address =this.findObject(this.option.column,'address');
              if(val=='03'){
                leader.display = true;
                phone.display = true;
                component.display = true;
                location.display = true;
                email.display = true;
                lng.display = true;
                lat.display = true;
                address.display = true;
              }else{
                leader.display = false;
                phone.display = false;
                component.display = false;
                location.display = false;
                email.display = false;
                lng.display = false;
                lat.display = false;
                address.display = false;
              }
            },
            immediate: true
          },
          // 'form.parentId':{
          //     handler(val){
          //         console.log("pid="+val);
          //         getCodeByPid(val).then(res => {
          //           console.log(res.data.data);
          //           this.form.deptCode=res.data.data.deptCode;
          //           this.form.sort = res.data.data.sort;
          //         });

          //     }
          // }
     },

    computed: {
      ...mapGetters(["userInfo", "permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.dept_add, false),
          viewBtn: this.vaildData(this.permission.dept_view, false),
          delBtn: this.vaildData(this.permission.dept_delete, false),
          editBtn: this.vaildData(this.permission.dept_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      nodeClick(data) {
        this.treeDeptId = data.id;
        this.page.currentPage = 1;
        this.parentId = data.id;
        this.onLoad(this.page);
      },

      openGrid(){
        console.log("form:",this.form)
        this.flowBox = true
      },

      //地图选择组件回调处理数据
      getGridMap(data){

        //数据处理
        if(data){
          console.log(data);
            let areaJson=JSON.parse(data);
            let gridDraw = "";
            if(areaJson.length>1){
               gridDraw = "MultiPolygon(";
              for (let i = 0; i <areaJson.length; i++){  //几个面
                  gridDraw +='((' ;
                  for(let j = 0; j < areaJson[i].length; j++){    //几个坐标点
                      var  str = areaJson[i][j].toString().replace(","," ");
                      console.log(areaJson[i].length+"----"+j)
                          if(areaJson[i].length===(j+1)){
                            gridDraw += str;
                          }else{
                              gridDraw += str+",";
                          }
                  }
                  if(areaJson.length===(i+1)){
                    gridDraw +='))' ;
                  }else{
                    gridDraw +=')),' ;
                  }

              }
               gridDraw += ")";
            }else{
                gridDraw +='Polygon((' ;
                  for(let j = 0; j < areaJson[0].length; j++){    //几个坐标点
                      var  str2 = areaJson[0][j].toString().replace(","," ");
                      console.log(areaJson[0].length+"----"+j)
                          if(areaJson[0].length===(j+1)){
                            gridDraw += str2;
                          }else{
                              gridDraw += str2+",";
                          }
                  }
                gridDraw += "))";
            }

            this.form.gridDraw = gridDraw
        }else{
          this.form.gridDraw = ''
        }

        this.flowBox = false
      },
      initData() {
        getDeptTree().then(res => {
          const column = this.findObject(this.option.column, "parentId");
          column.dicData = res.data.data;
        });
      },
      handleAdd(row) {
        this.$refs.crud.value.parentId = row.id;
        this.$refs.crud.option.column.filter(item => {
          if (item.prop === "parentId") {
            item.value = row.id;
            item.addDisabled = true;
          }
        });
        this.$refs.crud.rowAdd();
      },
      rowSave(row, done, loading) {
        add(row).then((res) => {
          // 获取新增数据的相关字段
          const data = res.data.data;
          row.id = data.id;
          row.deptCategoryName = data.deptCategoryName;
          row.tenantId = data.tenantId;
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          // 数据回调进行刷新
          done(row);
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          console.log("row_update:",row)
          // 数据回调进行刷新
          done(row);
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row, index, done) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            // 数据回调进行刷新
            done(row);
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            // 刷新表格数据并重载
            this.data = [];
            this.parentId = 0;
            this.$refs.crud.refreshTable();
            this.$refs.crud.toggleSelection();
            // 表格数据重载
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      searchReset() {
        this.query = {};
        this.parentId = 0;
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.parentId = '';
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      beforeOpen(done, type) {
        if (["add"].includes(type)) {
          setTimeout(() => {
            //新增时添加默认值
             this.form.parentId = this.parentId;
            this.form.deptCategory = 1,
            this.form.status = 0
          }, 100);
          if(this.parentId == null || this.parentId == ""){
             this.$message({
                    message: '请选择机构',
                    type: 'success'
            });
          }else{
           getCodeByPid(this.parentId).then(res => {
            this.form.deptCode=res.data.data.deptCode;
            this.form.sort = res.data.data.sort;
          });
          }
        }
        if (["add", "edit"].includes(type)) {
          this.initData();
        }
        if (["edit", "view"].includes(type)) {
          getDept(this.form.id).then(res => {
            this.form = res.data.data;
            console.log("edit:",res.data.data)
          });
        }
        done();
      },
      beforeClose(done) {
        this.$refs.crud.tableForm = {};
        this.$refs.crud.value.parentId = "";
        this.$refs.crud.value.addDisabled = false;
        this.$refs.crud.option.column.filter(item => {
          if (item.prop === "parentId") {
            item.value = "";
            item.addDisabled = false;
          }
        });
        done();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;

        getLazyList(this.parentId, Object.assign(params, this.query)).then(res => {
          this.data = res.data.data;
          this.loading = false;
          this.selectionClear();
        });
      },

    }
  };
</script>

<style>
.el-form-item__content{
   margin-left: 100px ! important;
}
.el-form-item__label {
  width: 100px ! important;
}
</style>

